import { Object3D, Scene } from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";

interface LoadingProgress {
  progress: number;
  loaded: number;
  total: number;
}

export default function createModel(
  _scene: Scene,
  onProgress?: (progress: LoadingProgress) => void
): Promise<Object3D> {
  return new Promise((resolve, reject) => {
    // 初始化加载器
    const loader = new GLTFLoader();
    // 加载模型
    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath(import.meta.env.BASE_URL + "draco/");
    loader.setDRACOLoader(dracoLoader);

    // Load a glTF resource
    loader.load(
      // resource URL
      import.meta.env.BASE_URL + "911-draco.glb",
      // called when the resource is loaded
      function (gltf) {
        const carModel = gltf.scene.children[0];
        carModel.name = "911";
        carModel.position.y += 0.63;
        _scene.add(gltf.scene);
        resolve(gltf.scene);
      },
      // called while loading is progressing
      function (xhr) {
        const progress = (xhr.loaded / xhr.total) * 100;
        onProgress?.({
          progress,
          loaded: xhr.loaded,
          total: xhr.total,
        });
      },
      // called when loading has errors
      function (error) {
        console.error("An error happened during model loading:", error);
        reject(error);
      }
    );
  });
}
